from _decimal import Decimal

from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.generics import CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import SKU
from orders.serializers import OrderSettlementSerializer, SaveOrderSerializer


class Order_Settlement(APIView):
    '''订单结算,说白了从redis查出来数据到订单页面展示'''
    '''往页面传输数据需要序列话器来进行序列化'''
    permission_classes = [IsAuthenticated]
    def get(self,request):
        # 要传数据你得要先查
        user_id=request.user.id
        redis_connect=get_redis_connection('cart')
        redis_dict = redis_connect.hgetall('cart_%s' % user_id)
        # redis_selected_dict = redis_connect.smembers('cart_selected_%s' % user_id)
        cart_select=redis_connect.smembers('cart_selected_%s' % user_id)
        # 拿到的是sku_id
        '''{b'1:b'1}'''
        # 这里要拿count
        '''如何拿count'''
        cart_dict={}
        for sku_id in cart_select:
            print(sku_id)
            cart_dict[int(sku_id)]=int(redis_dict[sku_id])
            '''{sku_id:count}'''
        goods=SKU.objects.filter(id__in=cart_dict.keys())
        freight=Decimal('10.00')
        for good in goods:
            good.freight=freight
            good.count=cart_dict[good.id]
        serializer=OrderSettlementSerializer({'freight': freight, 'skus': goods})
        return Response(serializer.data)

'''保存订单'''
'''往两张表中存数据'''
class Save_The_Order(CreateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class= SaveOrderSerializer
